<template>
  <van-popup v-model:show="state.show" class="popup-box" style="height: 100%" position="right">
    <div class="page">
      <global-header title="修改密码" @back="state.show = false"> </global-header>
      <main class="page-main">
        <van-field v-model="state!.Password" label="密码" placeholder="请输入密码"></van-field>
        <van-field
          v-model="state!.newPassword"
          label="确认密码"
          placeholder="请输入确认密码"
        ></van-field>
      </main>

      <div class="p-[15px] bg-[#FFFFFF]">
        <div class="flex gap-[10px]">
          <van-button
            @click="update"
            class="!flex-1 !bg-[#3976CC] !text-[#FFFFFF] rounded-[5px]"
            block
          >
            保存
          </van-button>
        </div>
      </div>
    </div>
  </van-popup>
</template>

<script lang="ts" setup>
import { debounce } from "lodash-es";
import { reqUserResetPassword } from "@/api/user";
import { showSuccessToast } from "vant";
import { usePremsStore } from "@/store/modules/prems";
import { toast } from "@/utils/toast";

const props = withDefaults(
  defineProps<{
    uid: number | null;
  }>(),
  {}
);

const premsStore = usePremsStore();
const emit = defineEmits<{
  (event: "update"): void;
}>();

const state = reactive({
  show: false,
  newPassword: "",
  Password: ""
});

const update = debounce(
  async () => {
    if (!premsStore.isEditUserSetting) {
      toast.info("暂无权限");
      return;
    }
    if (!props.uid) {
      return showToast("非法操作");
    }
    if (!state.Password) {
      return showToast("请输入密码");
    }
    if (!state.newPassword) {
      return showToast("请输入确认密码");
    }
    if (state.Password != state.newPassword) {
      return showToast("确认密码不正确");
    }
    try {
      await reqUserResetPassword({
        UserId: props.uid,
        Password: state.Password,
        newPassword: state.newPassword
      });
      emit("update");
      showSuccessToast("修改密码成功");
      setTimeout(() => {
        closed();
      }, 200);
    } catch (error) {
      console.log(error);
    }
  },
  500,
  { leading: true, trailing: false }
);

const closed = () => {
  state.show = false;
};

const open = () => {
  state.show = true;
  state.newPassword = "";
  state.Password = "";
};
defineExpose({
  closed,
  open
});
</script>
